package com.jiwei.community.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiwei.community.dao.UserMapper;
import com.jiwei.community.entity.LoginUser;
import com.jiwei.community.entity.User;
import com.jiwei.community.enums.AppHttpCodeEnum;
import com.jiwei.community.exception.SystemException;
import com.jiwei.community.service.LoginService;
import com.jiwei.community.service.UserService;
import com.jiwei.community.utils.BeanCopyUtils;
import com.jiwei.community.utils.JwtUtils;
import com.jiwei.community.utils.RedisCache;
import com.jiwei.community.vo.ResponseResult;
import com.jiwei.community.vo.UserInfoVo;
import com.jiwei.community.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author 季伟
 * 功能：
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager ;
    @Autowired
    private RedisCache redisCache;
    @Resource(type = UserMapper.class)
    UserMapper userMapper;
    @Resource
    UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public ResponseResult login(User loginUser) {

        //创建用来认证的authentication，它封装了用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser.getUserName(),loginUser.getPassword());
        //使用AuthenticationManager的authenticate方法进行用户认证，这个方法内部会调用一个UserDetailService进行用户信息获取
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);//调用该方法进行验证
        if (Objects.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR,"用户认证失败");
        }
        //principal是一个userDetail对象也就是userDetailService返回的值。
        LoginUser userDetails = (LoginUser) authenticate.getPrincipal();

        //利用jwt创建 token
        String token = JwtUtils.createJWT(userDetails.getCacheUser().getId().toString());
        userDetails.setToken(token);
        redisCache.setCacheObject("login:"+userDetails.getCacheUser().getId(),userDetails,3, TimeUnit.HOURS);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(userDetails.getUser(), UserInfoVo.class);
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setToken(token);
        userLoginVo.setUserInfo(userInfoVo);
        if(userDetails.getUser().getType() == 1){
            userLoginVo.setRoles(userDetails.getRoles());
            userLoginVo.setPerms(userDetails.getPermissions());
        }
        return new ResponseResult(200,"登录成功",userLoginVo);
    }

    @Override
    public ResponseResult logout() {
        //获取验证过滤器解析token获得的验证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //从验证对象中获取当前的用户
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getCacheUser().getId();
        boolean isDeleted = redisCache.deleteObject("login:"+userId);
        if (isDeleted){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),"注销成功！");
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"注销失败");
        }

    }

    @Override
    public ResponseResult register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return ResponseResult.okResult("注册成功");
    }

    @Override
    public ResponseResult isLogin(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User user = userService.getOne(queryWrapper);
        if (user == null)return ResponseResult.errorResult(AppHttpCodeEnum.BAD_REQUEST,"用户名不正确");
        LoginUser loginUser = redisCache.getCacheObject("login:"+user.getId());
        Map<String,Object> map = new HashMap<>();

        if (loginUser == null){
            map.put("isLogin",false);
            return ResponseResult.okResult(map);
        }
        map.put("isLogin",true);
        map.put("userInfo",loginUser.getCacheUser());
        map.put("roles",loginUser.getRoles());
        map.put("perms",loginUser.getPermissions());
        map.put("token",loginUser.getToken());
        return  ResponseResult.okResult(map);
    }

}
